﻿
import com.kirillam.handy.core.HATObject;

import com.kirillam.handy.events.HATEvent;



/**
* Sends pulse events every specified number of miliseconds.
* 
* @author Kirill Mourzenko
*/

class com.kirillam.handy.repeaters.HATTimer extends HATObject
{
	private	var intId		: Number;
	private var pulses		: Number;
	
	
	/**
	 * Constructor
	 */
	
	public function HATTimer( interval : Number, pulses : Number ) 
	{
		super();
	}
	
	
	/*
	 * Sends pulse events.
	 */
	
	private function onTimer()
	{
		pulses--;
			
		sendEvent( new HATEvent( HATEvent.PULSE ) );
			
		if ( pulses <= 0 ) {
			clearInterval( intId );
			sendEvent( new HATEvent( HATEvent.STOP ) );
		}
	}
	
	
	/**
	 * Starts the timer.
	 * 
	 * @param	interval	Number of miliseconds between pulse events.
	 * @param	pulses		Number of pulses to make. If null then there's no limit on number of pulses.
	 */
	
	public function start( interval : Number, pulses : Number )
	{
		if ( pulses != null && pulses > -1 ) {
			this.pulses	= pulses;
		} else {
			this.pulses	= Number.POSITIVE_INFINITY;
		}
		
		intId			= setInterval( this, "onTimer", interval );
	}
	
	
	/** Stops the timer. */
	
	public function kill()
	{
		clearInterval( intId );
		intId	= null;
	}
	
	
	/** 
	 * Tells if the timer is running.
	 *
	 * @return	true if the timer is running, false otherwise.
	 */
	
	public function isActive() : Boolean
	{
		return intId != null;
	}
}